package Work.com;

import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

public class Exam01 {
    //给定两个字符串，编写一个函数来获取这两个字符串的最长公共子序列。
    public static String longestPublicString(String str1, String str2){
        String newstr = "";
        char[] ch = str1.toCharArray();
        char[] ch1 = str2.toCharArray();
        if (ch.length >= ch1.length) {
            for (int i = 0; i < ch.length; i++) {
                for (int j = 0; j < ch1.length; j++) {
                    if (Objects.equals(ch[i], ch1[j])) {
                        newstr += ch[i];
                    }
                }
            }
        }
        else {
            for (int i = 0; i < ch1.length; i++) {
                for (int j = 0; j < ch.length; j++) {
                    if (Objects.equals(ch1[i], ch[j])) {
                        newstr += ch1[i];
                    }
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <newstr.length() ; i++) {
            if (newstr.indexOf(newstr.charAt(i)) == i){
                sb.append(newstr.charAt(i));
            }
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串：");
        String str1 = sc.next();
        System.out.println("请输入字符串：");
        String str2 = sc.next();

        System.out.println(longestStringlength(str1,str2));

    }
    public static int  longestStringlength(String  str1 , String str2){
        int m = str1.length();
        int n = str2.length();
        int[][] str =new int[m + 1][n + 1];
        for (int i = 1; i <= m ; i++) {
            for (int j = 1; j <= n ; j++) {
                if (Objects.equals(str1.charAt(i - 1),str2.charAt(j - 1))){
                    str[i][j] = str[i - 1][j - 1] + 1;
                }else {
                    str[i][j] = Math.max(str[i - 1][j],str[i][j - 1] );
                }
            }
        }

        return str[m][n];
    }
}

